# https://blog.csdn.net/oscar_liu/article/details/81210301
# 有点问题

import sys
import cv2
import numpy as np

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *


class Video():
    def __init__(self, capture):
        self.capture = capture
        self.currentFrame = np.array([])

    def captureFame(self):
        # 读取capture，获取frame,返回readFrame
        ret, readFrame = self.capture.read()
        return readFrame

    def captureNextFrame(self):
        # 正确读取一帧后，进行颜色转换，并存入初始化的self.currentFrame中
        ret, readFrame = self.capture.read()
        if (ret):
            self.currentFrame = cv2.cvtColor(readFrame, cv2.COLOR_BAYER_BG2RGB)

    def convertFrame(self):
        try:
            height, width = self.currentFrame.shape[:2]
            img = QImage(self.currentFrame,
                         width,
                         height,
                         QImage.Format_RGB888)
            img = QPixmap.fromImage(img)
            self.previousFrame = self.currentFrame
            return img
        except:
            return None


class Gui(QMainWindow):
    def __init__(self):

        super().__init__()
        self.setGeometry(250, 80, 800, 600)
        self.setWindowTitle("测试")
        self.video = Video(cv2.VideoCapture(0))
        self._timer = QTimer(self)
        self._timer.timeout.connect(self.play)
        self._timer.start(27)
        self.update()
        self.videoFrame = QLabel("VideoCapture")
        self.videoFrame.setAlignment(Qt.AlignCenter)
        self.setCentralWidget(self.videoFrame)

        self.ret, self.captureFrame = self.video.capture.read()

    def play(self):
        try:
            self.video.captureNextFrame()
            self.videoFrame.setPixmap(self.video.convertFrame())
            self.videoFrame.setScaledContents(True)
        except TypeError:
            print("No Frame")


if __name__ == "__main__":
    app = QApplication(sys.argv)

    ex = Gui()


    ex.show()


    sys.exit(app.exec_())
